import React, { useState, useEffect } from 'react';
import ConfirmDialog from './ConfirmDialog'; // 引入自定义确认对话框组件

interface IProps {
    currentTab: string;
    addTodoItem: (value: string) => void;
    allCompleted: boolean;
    toggleAllTodos: (shouldCompleteAll: boolean) => void;
    counts: {
        totalCount: number,
        pendingCount: number,
        completedCount: number
    };
}

const MainHeader: React.FC<IProps> = ({ currentTab, addTodoItem, allCompleted, toggleAllTodos, counts}) => {
    const [isAllCompleted, setIsAllCompleted] = useState(allCompleted);
    const [inputValue, setInputValue] = useState('');
    const [isFocused, setIsFocused] = useState(() => {
        const storedIsFocused = localStorage.getItem('isFocused');
        return storedIsFocused === 'true';
    });
    const [showConfirm, setShowConfirm] = useState(false);
    const [confirmTitle, setConfirmTitle] = useState('');
    const [confirmMessage, setConfirmMessage] = useState('');

    useEffect(() => {
        console.info("allCompleted====>", allCompleted)
        setIsAllCompleted(allCompleted);
    }, [allCompleted]);

    useEffect(() => {
        // 当isFocused改变时，保存状态到本地存储
        localStorage.setItem('isFocused', isFocused.toString());
    }, [isFocused]);

    const handleFocus = () => {
        setIsFocused(true);
    };

    const handleBlur = () => {
        setIsFocused(false);
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setInputValue(e.target.value);
    };

    const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            addTodoItem(inputValue);
            setInputValue('');
        }
    };

    const handleToggleAllChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // 如果全选按钮是禁用状态，就直接返回
        if (getCheckAllIsDisabled()) {
            return;
        }

        const isChecked = e.target.checked;
        if (isChecked) {
            setConfirmTitle('标记为完成');
            setConfirmMessage('确定要将所有任务项标记为已完成吗？');
        } else {
            setConfirmTitle('标记为待完成');
            setConfirmMessage('确定要将所有任务项标记为待完成吗？');
        }
        setShowConfirm(true); // 显示确认对话框
    };

    const handleCheckAllIconClick = (e: React.MouseEvent<HTMLLabelElement>) => {
        e.preventDefault();

        // 如果全选按钮是禁用状态，就直接返回
        if (getCheckAllIsDisabled()) {
            return;
        }

        const isChecked = !isAllCompleted;
        if (isChecked) {
            setConfirmTitle('标记为完成');
            setConfirmMessage('确定要将所有任务项标记为已完成吗？');
        } else {
            setConfirmTitle('标记为待完成');
            setConfirmMessage('确定要将所有任务项标记为待完成吗？');
        }
        setShowConfirm(true); // 显示确认对话框
    };

    const handleConfirm = () => {
        setIsAllCompleted(!isAllCompleted);
        toggleAllTodos(!isAllCompleted);
        setShowConfirm(false);
    };

    const handleCancel = () => {
        setShowConfirm(false);
    };

    const getCheckAllTitle = () => {
        if (
            (currentTab === 'all' && counts.totalCount <= 0) ||
            (currentTab === 'pending' && counts.pendingCount <= 0) ||
            (currentTab === 'completed' && counts.completedCount <= 0)
        ) {
            return "";
        }

        if (isAllCompleted) {
            return "全部标记为待完成";
        } else {
            return "全部标记为完成";
        }
    }

    const getCheckAllIsDisabled = () => {
        return (
            (currentTab === 'all' && counts.totalCount <= 0) ||
            (currentTab === 'pending' && counts.pendingCount <= 0) ||
            (currentTab === 'completed' && counts.completedCount <= 0)
        );
    }

    return (
        <div className="main-header">
            <input className="toggle-all" type="checkbox" disabled={getCheckAllIsDisabled()} checked={isAllCompleted} onChange={handleToggleAllChange} />
            {!isFocused && <label className="check-all-icon" title={getCheckAllTitle()} onClick={handleCheckAllIconClick} />}
            {isFocused && <label className="write-do-icon" title="请从这里开始……" />}
            <input
                className="input-value"
                placeholder="接下来要做什么呢？"
                onFocus={handleFocus}
                onBlur={handleBlur}
                onChange={handleInputChange}
                onKeyUp={handleKeyUp}
                value={inputValue}
                autoFocus={isFocused}
            />
            <ConfirmDialog
                isOpen={showConfirm}
                title={confirmTitle}
                message={confirmMessage}
                onConfirm={handleConfirm}
                onCancel={handleCancel}
            />
        </div>
    );
};

export default MainHeader;